<?php

namespace App\Api\Controllers;

use App\Models\Sms;
use App\Models\UserInterest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\User;
use JWTAuth;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        // 手机号码验证
        if (!preg_match('/^1[3456789]\d{9}$/', $request->mobile)) {
            return $this->responseFailed('手机号码格式不正确');
        }
        if (!$request->code) {
            return $this->responseFailed('验证码错误');
        }
        $sms = Sms::where(['mobile'=>$request->mobile])
            ->orderBy('id', 'desc')
            ->first();
        if(!$sms){
            return $this->responseFailed('手机号码输入不正确');
        }
        if($sms->code != $request->code){
            return $this->responseFailed('验证码输入不正确');
        }
        $user = User::where(['mobile'=>$request->mobile])->first();

        if($user && !$user->status){
            return $this->responseFailed('账号已被禁用');
        }
        $token = JWTAuth::fromUser($user);
        $user->token = $token;
        return $this->responseData($user->toArray());
       /* // 短信验证码验证
       if (!preg_match('/^1[3456789]\d{9}$/', $request->mobile)) {
            return $this->responseFailed('手机号码格式不正确');
        }
       if (!$request->code) {
            return $this->responseFailed('验证码错误');
        }
        $sms = Sms::where(['mobile'=>$request->mobile])
            ->orderBy('id', 'desc')->first();

        if(!$sms){
            return $this->responseFailed('手机号码输入不正确');
        }
        if($sms->code != $request->code){
            return $this->responseFailed('验证码输入不正确');
        }
         */
    }

    /**
     * 注册
     */
    public function reg(Request $request)
    {
        // 短信验证码验证
        $sms = Sms::where(['mobile'=>$request->mobile])
            ->orderBy('id', 'desc')->first();

        if(!$sms){
            return $this->responseFailed('手机号码输入不正确');
        }

        if($sms->code != $request->code){
            return $this->responseFailed('验证码输入不正确');
        }
        $user = User::where(['mobile'=>$request->mobile])->first();
        if($user){
            return $this->responseFailed('已注册');
        }
        $input = $request->all();
        unset($input['code']);
        $user = new User();
        foreach ($input as $key=>$val) {
            $user->$key = $val;
        }
        if ($user->save()) {
            $token = $token = JWTAuth::fromUser($user);
            $user->token = $token;
            return $this->responseData($user->toArray());
        }
        return $this->responseFailed();
    }

    /**
     * 注册手机号检测
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkReg(Request $request)
    {
        // 手机号码验证
        if (!preg_match('/^1[3456789]\d{9}$/', $request->mobile)) {
            return $this->responseFailed('手机号码格式不正确');
        }
        $user = User::where(['mobile'=>$request->mobile])->first();
        if($user){
            return $this->responseFailed('已注册');
        }
        return $this->responseSuccess('未注册');
    }

    public function userInterest()
    {
        $data = UserInterest::all();
        if($data){
        }
        $data = $data?$data->toArray():[];
        return $this->responseData($data);
    }

    /**
     * @OA\Post(
     *     path="/api/sms",
     *     tags={"公共接口"},
     *     summary="短信验证码",
     *     description="获取短信验证码接口",
     *     operationId="auth_smsCode",
     *     deprecated=false,
     *     @OA\Parameter(name="mobile", in="query", description="手机号码", required=true,
     *          @OA\Schema( type="string")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="操作成功返回"
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="发生错误"
     *     )
     * )
     */
    public function smsCode(Request $request)
    {
        // 手机号码验证
        if(!preg_match('/^1[345789]\d{9}$/', $request->mobile)){
            return $this->responseFailed('手机号码格式不正确');
        }
        $param = [
            'templet_id' => 'SMS_159040007',
            'mobile' => $request->mobile,
            'content' => [
                'code' => mt_rand(100000, 999999),
            ],
            'ip' => $request->getClientIp(),
        ];
        if(!$result = sms_send($param)){
            return $this->responseFailed('发送失败');
        }
        return $this->responseSuccess($param['content']['code']);
    }

    public function upfile(Request $request)
    {
        if (!$request->hasFile('img')) {
            return $this->responseFailed('请选择上传文件');
        }
        $type = [
            1 => 'avatar',
            2 => 'article',
            3 => 'card',
        ];
        if (!array_key_exists($request->upload_type, $type)) {
            return $this->responseFailed('上传类型错误');
        }
        $path = $request->img->store($type[$request->upload_type]);
        $data = [
            $request->root().'/uploads/'.$path,
        ];
        return $this->responseData($data);
    }
}
